package com.kuiandjie.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kuiandjie.entity.Idea;
import com.kuiandjie.util.DBHelp;
import com.kuiandjie.util.RowMapper;

public class IdeaDao {
	private DBHelp<Idea> db = new DBHelp<Idea>();
	
	private class IdeaMap implements RowMapper<Idea>{

		@Override
		public Idea mapperRow(ResultSet rs) throws SQLException {
			Idea idea = new Idea();
			idea.setContent(rs.getString("content"));
			idea.setCreatetime(rs.getString("createtime"));
			idea.setEmployeeId(rs.getInt("employeeid"));
			idea.setId(rs.getInt("id"));
			idea.setProjectId(rs.getInt("projectid"));
			idea.setTitle(rs.getString("title"));
			idea.setName(rs.getString("name"));
			return idea;
		}
	}
	
	public List<Idea> findAllByProjectId(int id) {
		String sql = "SELECT a.id, title, content, createtime, employeeid, projectid, b.name AS name FROM t_idea AS a, t_employee AS b WHERE a.employeeid = b.id AND a.projectid = ? ORDER BY createtime DESC";
		return db.executeQueryForList(sql, new IdeaMap(), id);
	}

	public int insertIdea(Idea i) {
		String sql = "INSERT INTO t_idea (title, content, createtime, employeeid, projectid) VALUES (?, ?, ?, ?, ?)";
		return db.getAutoKey(sql, i.getTitle(), i.getContent(), i.getCreatetime(), i.getEmployeeId(), i.getProjectId());
	}

	public Idea findIdeaById(int id) {
		String sql = "SELECT a.id, title, content, createtime, employeeid, projectid, b.name AS name FROM t_idea AS a, t_employee AS b WHERE a.employeeid = b.id AND a.id = ?";
		return db.executeQueryForObject(sql, new IdeaMap(), id);
	}

	public void updateIdea(Idea i) {
		String sql = "UPDATE t_idea SET content = ?, title = ? WHERE id = ?";
		db.executeSQL(sql, i.getContent(), i.getTitle(), i.getId());
	}
}
